package com.zxp.quartz.demo.config;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

/**
 *
 * 将Spring的对象注入到Quartz Job 2
 */
@Component
public class MyJobFactory extends AdaptableJobFactory {

    //AutowireCapableBeanFactory接口是BeanFactory的子类，可以连接和填充那些生命周期不被Spring管理的已存在的bean实例
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    //重写创建Job任务的实例方法
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);

        //通过以下方式，解决Job任务无法使用Spring中的Bean问题
        capableBeanFactory.autowireBean(jobInstance);

        return jobInstance;
    }
}